import { defineStore } from 'pinia';
import { computed, reactive, watchEffect } from 'vue';
import { theme as antdTheme } from 'ant-design-vue';
import { getSystemTheme, useDebounce } from '@/hooks/index.js';
import { underscore } from 'inflection';

const useStore = defineStore(
  'app-store',
  () => {
    const defaultConfig = {
      theme: 'auto',
      sideDark: true,
      tabsEnable: true,
      layoutMode: 'side',
      layout: {
        headerHeight: 53,
        sideWidth: 200,
        sideWidthCollapse: 64,
        tabsHeight: 40
      },
      token: {
        colorPrimary: '#1677FF',
        colorSuccess: '#52C41A',
        colorWarning: '#FAAD14',
        colorError: '#F5222D'
      }
    };

    const themeConfig = reactive(defaultConfig);
    // const systemTheme = computed(() => (themeConfig.theme === 'auto' ? getSystemTheme() : themeConfig.theme));

    function setupTheme(target) {
      watchEffect(() => {
        const systemTheme = themeConfig.theme === 'auto' ? getSystemTheme() : themeConfig.theme;
        target?.setAttribute('data-theme', systemTheme);
        themeConfig.algorithm = systemTheme === 'dark' ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm;
        themeConfig.systemTheme = systemTheme;
        let style = '';
        for (const key in themeConfig.layout) {
          let value = themeConfig.layout[key];
          if (Number.isFinite(value)) {
            value += 'px';
            style += `--layout-${underscore(key).replaceAll('_', '-')}: ${value}; `;
          }
        }

        target.setAttribute('style', style);
      });
    }

    /**
     * 更新主题
     *
     * @param key
     * @param value
     */
    function updateTheme(key, value) {
      if (themeConfig[key] !== value) {
        themeConfig[key] = value;
      }
    }

    /**
     * 更新主题颜色
     *
     * @param key
     * @param value
     */
    function updateThemeColor(key, value) {
      if (themeConfig.token[key] !== value) {
        themeConfig.token[key] = value;
      }
    }

    /**
     * 更新主题布局
     *
     * @param key
     * @param value
     */
    function updateThemeLayout(key, value) {
      if (themeConfig.layout[key] !== value) {
        themeConfig.layout[key] = value;
      }
    }

    function updateConfig(config) {
      delete config.algorithm;
      config = {
        ...themeConfig,
        ...config,
        token: { ...themeConfig.token, ...config.token }
      };
      const store = useStore();
      store.$patch({ themeConfig: config });
    }

    return {
      themeConfig,
      defaultConfig,
      setupTheme,
      updateConfig,
      updateTheme,
      updateThemeColor: useDebounce(updateThemeColor, 100),
      updateThemeLayout
    };
  },
  {
    storage: {
      enable: true, // 开启存储功能
      key: 'setting', // 存储的key
      aloneFields: true // 是否单独存储字段
    }
  }
);

export default useStore;
